﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using TTServer.Messages;
using System.IO;
using System.Diagnostics;
using TTServer.Objects;
using libSecuritySystem;
using libUtilities;
using System.Drawing.Imaging;

namespace TTServer
{
    public partial class FormServerGUI : Form
    {
        private SocketServer m_socketServer = null;
        private BluetoothServer m_bluetoothServer = null;

        private Image SilverBGImage = null;

        public FormServerGUI()
        {
            InitializeComponent();

            m_socketServer = new SocketServer();

            m_bluetoothServer = new BluetoothServer();
            m_bluetoothServer.StartBluetooth();

            //if (m_bluetoothServer.NotSupported)
            //{
            //    MessageBox.Show("Bluetooth not supported");
            //}
            //else {
            //    MessageBox.Show("Bluetooth supported");
            //}

            if (m_socketServer != null)
            {
                m_socketServer.Start();
            }

            //AuthenManagement.getInstance().NMemberSystem = new k_n_ThresholdModel(5, 2, 10);
        }

        private void RefreshPresentationNames()
        {
            PPTController pptCtrl = PPTController.Instance;

            if (pptCtrl != null)
            {
                String[] names = pptCtrl.GetPresentationNames();

                String activePresentationName = pptCtrl.GetActivePresentationName();


                if (names != null && activePresentationName != null)
                {
                    cmbPresentations.Items.Clear();

                    if (names.Length > 0)
                    {
                        int nNames = names.Length;

                        for (int i = 0; i < nNames; i++)
                        {
                            cmbPresentations.Items.Add(names[i]);

                            if (names[i] == activePresentationName)
                            {
                                cmbPresentations.SelectedIndex = i;
                            }
                        }
                    }
                    else
                    {
                        cmbPresentations.Text = "";
                    }
                }
            }
            else
            {
                MessageBox.Show("pptCtrl chưa được khởi tạo thành công.");
            }
        }


        private void Start()
        {
            PPTController pptCtrl = PPTController.Instance;

            pptCtrl.Start();
        }

        private void Open(String filePath)
        {
            try
            {
                PPTController pptCtrl = PPTController.Instance;

                if (pptCtrl != null)
                {
                    pptCtrl.Open(filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            RefreshPresentationNames();
        }

        private void UpdateSlideImage()
        {
            if (PPTController.Instance.checkSlideShowActivated() == 1)
            {
                Image img = PPTController.Instance.GetSlideImage();

                pbSlideShow.Image =
                    ImageUtils.resizeImage(img, new Size(pbSlideShow.Width, pbSlideShow.Height));
            }
            else
            {
                pbSlideShow.Image = null;
            }
        }



        private void Open()
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Powerpoint Presentations 2003 (*.ppt)|*.ppt|Powerpoint Presentations 2007 or 2010 (*.pptx)|*.pptx";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String filePath = dlg.FileName;

                Open(filePath);
            }
        }

        private void Prev()
        {
            PPTController pptCtrl = PPTController.Instance;
            pptCtrl.PrevSlide();
            UpdateSlideImage();
        }

        private void Next()
        {
            PPTController pptCtrl = PPTController.Instance;

            int kq = pptCtrl.IsEndingSlide();

            if (kq == -1)
            {
                MessageBox.Show("Thao tác không hợp lệ.");
            }
            else if (kq == 0)
            {
                pptCtrl.NextSlide();

                UpdateSlideImage();
            }
            else if (kq == 1)
            {
                MessageBox.Show("Đã tới slide cuối cùng.");
            }
        }

        private void Stop()
        {
            PPTController pptCtrl = PPTController.Instance;

            pptCtrl.EndShow();

            UpdateSlideImage();
        }

        private void Close()
        {
            PPTController.Instance.CloseActiveWindow();
            RefreshPresentationNames();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            Open();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshPresentationNames();
        }

        private void btnSlideShow_Click(object sender, EventArgs e)
        {

            int result = PPTController.Instance.Start();

            if (result == 1)
            {
                UpdateSlideImage();
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            Prev();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            Next();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnRefreshPB_Click(object sender, EventArgs e)
        {
            UpdateSlideImage();
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            Random rd = new Random(System.DateTime.Now.Millisecond);
            double rdf = rd.NextDouble();
            int rdPort = 2000 + (int)((60000 - 2000) * ((float)rdf));
            txtPort.Text = rdPort.ToString();
            SocketServer.port = rdPort;


        }

        private void OnTheButtonUseClicked()
        {
            if (m_socketServer != null)
            {
                //try
                //{
                //    SocketServer.port = Int32.Parse(txtPort.Text);
                //}
                //catch
                //{
                //    SocketServer.port = 44472;
                //}
                m_socketServer.Start();
            }
        }

        private void btnUse_Click(object sender, EventArgs e)
        {
            OnTheButtonUseClicked();
        }

        private void btnTerminate_Click(object sender, EventArgs e)
        {
            if (m_socketServer != null)
            {
                m_socketServer.Terminate();
            }
        }

        private void cmbPresentations_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbPresentations.SelectedIndex >= 0)
                {
                    PPTController pptCtrl = PPTController.Instance;

                    pptCtrl.SetActivePresentationIndex(cmbPresentations.SelectedIndex);
                }
            }
            catch
            {
                MessageBox.Show("Thao tác ko dc thực hiện thành công.");
            }
        }

        private void ServerGUI_Load(object sender, EventArgs e)
        {
            //FileExplorer fe = new FileExplorer(null);
            //List<string> files = fe.exploreDirectoryReturnDirList_opt2("C:\\Documents and Settings\\");

            //List<string> drivers = fe.exploreRoots();
            //List<string> files_1 = fe.exploreDirectoryReturnDirList_opt2(drivers[0]);
            //List<string> files_2 = fe.exploreDirectoryReturnDirList_opt2(files_1[15]);
            //List<string> files_3 = fe.exploreDirectoryReturnDirList_opt2(files_1[15] + "//");

            //string temp = files_1[15] + "\\";
            ////MessageBox.Show(temp);
            //List<string> files_4 = fe.exploreDirectoryReturnDirList_opt2(temp);
            //List<string> files_9 = fe.exploreDirectoryReturnFileList(temp);

            //temp = files_1[15] + "\\\\";
            ////MessageBox.Show(temp);
            //List<string> files_5 = fe.exploreDirectoryReturnDirList_opt2(temp);

            //List<string> files_6 = fe.exploreDirectoryReturnDirList_opt2("C:");
            //List<string> files_7 = fe.exploreDirectoryReturnDirList_opt2("C:\\\\");
            //List<string> files_8 = fe.exploreDirectoryReturnDirList_opt2("C");

            SilverBGImage = new Bitmap(pbSlideShow.Width, pbSlideShow.Height);
            Graphics g = Graphics.FromImage(SilverBGImage);
            g.Clear(Color.Silver);
            g.Dispose();
            pbSlideShow.Image = SilverBGImage;

            //After this call, an unique instance for the class PPTController is created if no instance existing.
            //PPTController.CreateAnInstanceForClass();
        }



        private void ServerGUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (PPTController.HasInstanceNotNull())
            {
                PPTController.Instance.EndShow();

                if (PPTController.Instance.CheckNoPresentationOpen() == 1) // Trường hợp 0, -1 ko cần giải quyết
                {
                    PPTController.Instance.QuitPowerpoint();
                }
            }

            // Shutdown all Threads


            // Shutdown all server
            if (m_socketServer != null)
            {
                m_socketServer.Terminate();
            }

            if (m_bluetoothServer != null)
            {
                m_bluetoothServer.StopBluetooth();
            }
        }

        private void ServerGUI_FormClosed(object sender, FormClosedEventArgs e)
        {


        }

        private void btnTest_Click(object sender, EventArgs e)
        {

        }

        private void btnDraw_Click(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            int n = (int)(768 * 72.0 / g.DpiX);
            g.Dispose();

            int[] points = new int[] { 0, 0, 100, 100, 20, 20, 60, 20, 60, 80, 20, 40 };
            Size screenSize = new Size(100, 100);
            PPTController.Instance.Draw(points, screenSize);

            int[] points_2 = new int[] { 0, 0, 99, 0, 99, 99, 0, 99, 0, 0 };
            Size screenSize_2 = new Size(100, 100);
            PPTController.Instance.Draw(points_2, screenSize_2);

            PPTController.Instance.Draw_2();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            PPTController.Instance.exportToPNG();
        }

        private void btnTest1_Click(object sender, EventArgs e)
        {
            PPTController.Instance.GetAllSlideNumberAndSlideTitle();
        }

        private void btnTest2_Click(object sender, EventArgs e)
        {
            ScreenshotBroadcastWithFeedback.TryToStart();
        }

        private void btnCloseActiveWindow_Click(object sender, EventArgs e)
        {
            PPTController.Instance.CloseActiveWindow();
        }

        private void btnCloseAllWindow_Click(object sender, EventArgs e)
        {
            PPTController.Instance.CloseAll();
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            PPTController.Instance.QuitPowerpoint();
        }

        private void btnLaunchPPT_Click(object sender, EventArgs e)
        {
            PPTController.CreateAnInstanceForClass();
        }

        private void btnMaximizeWindow_Click(object sender, EventArgs e)
        {
            PPTController.Instance.Maximize();
        }

        private void btnMinimizeWindow_Click(object sender, EventArgs e)
        {
            PPTController.Instance.Minimize();
        }

        private void btnBlackScreen_Click(object sender, EventArgs e)
        {
            PPTController.Instance.SendBKeyToSlideShow();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PPTController.Instance.SendSlideShowClick(500, 500);
        }

        private void btnWhiteScreen_Click(object sender, EventArgs e)
        {
            PPTController.Instance.SendWKeyToSlideShow();
        }

        private void button2_Click(object sender, EventArgs e)
        {

            PPTController.Instance.SendSlideShowClick2(0.5, 0.5);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            CaptureScreen();
        }

        private Bitmap CaptureScreen()
        {
            Size size = new Size(Screen.PrimaryScreen.Bounds.Width,
                Screen.PrimaryScreen.Bounds.Height);

            Bitmap bitmap = new Bitmap(size.Width, size.Height);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.CopyFromScreen(new Point(0, 0), new Point(0, 0), size);
            }

            bitmap.Save("I:\\bmp00.jpg", ImageFormat.Jpeg);

            //Bitmap bmp = MakeGrayscale2(bitmap);
            Bitmap bmp = convertToGrayScale(bitmap);

            bmp.Save("I:\\bmp01.jpg", ImageFormat.Jpeg);

            return null;
        }

        public static Bitmap MakeGrayscale2(Bitmap original)
        {
            unsafe
            {
                //create an empty bitmap the same size as original
                Bitmap newBitmap = new Bitmap(original.Width, original.Height);

                //lock the original bitmap in memory
                BitmapData originalData = original.LockBits(
                   new Rectangle(0, 0, original.Width, original.Height),
                   ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                //lock the new bitmap in memory
                BitmapData newData = newBitmap.LockBits(
                   new Rectangle(0, 0, original.Width, original.Height),
                   ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

                //set the number of bytes per pixel
                int pixelSize = 3;

                for (int y = 0; y < original.Height; y++)
                {
                    //get the data from the original image
                    byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride);

                    //get the data from the new image
                    byte* nRow = (byte*)newData.Scan0 + (y * newData.Stride);

                    for (int x = 0; x < original.Width; x++)
                    {
                        //create the grayscale version
                        byte grayScale =
                           (byte)((oRow[x * pixelSize] * .11) + //B
                           (oRow[x * pixelSize + 1] * .59) +  //G
                           (oRow[x * pixelSize + 2] * .3)); //R

                        //set the new image's pixel to the grayscale version
                        nRow[x * pixelSize] = grayScale; //B
                        nRow[x * pixelSize + 1] = grayScale; //G
                        nRow[x * pixelSize + 2] = grayScale; //R
                    }
                }

                //unlock the bitmaps
                newBitmap.UnlockBits(newData);
                original.UnlockBits(originalData);

                return newBitmap;
            }
        }

        private Bitmap convertToGrayScale(Bitmap image)
        {
            // lock the bitmap.
            var data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            try
            {
                unsafe
                {
                    // get a pointer to the data.
                    byte* ptr = (byte*)data.Scan0;

                    // loop over all the data.
                    for (int i = 0; i < data.Height; i++)
                    {
                        for (int j = 0; j < data.Width; j++)
                        {
                            // calculate the gray value.
                            byte y = (byte)((0.299 * ptr[2]) + (0.587 * ptr[1]) + (0.114 * ptr[0]));

                            // set the gray value.
                            ptr[0] = ptr[1] = ptr[2] = y;

                            // increment the pointer.
                            ptr += 3;
                        }

                        // move on to the next line.
                        ptr += data.Stride - data.Width * 3;
                       
                    }
                }
            }
            finally
            {
                // unlock the bits when done or when 
                // an exception has been thrown.
                image.UnlockBits(data);
            }
            return image;
        }
    }
}
